<template>
  <t-dialog
    v-model:visible="visible"
    :header="dialogTitle"
    width="700"
    :confirm-btn="{ loading }"
    @confirm="dialogConfirm"
    @close="dialogHide"
  >
    <t-space direction="vertical" style="width: 100%">
      <t-form ref="form" reset-type="initial" :data="formData" :rules="FORM_RULES" :label-width="120">
        <t-form-item :label="t('pages.role.name')" name="name" initial-data="">
          <t-input v-model="formData.name" maxlength="32" show-limit-number />
        </t-form-item>
        <t-form-item :label="t('pages.role.desc')" name="description">
          <t-textarea
            v-model="formData.description"
            :autosize="{ minRows: 2, maxRows: 4 }"
            resize="none"
            maxlength="250"
            show-limit-number
          />
        </t-form-item>

        <t-form-item :label="t('pages.role.permission')" name="menus">
          <div style="width: 100%; overflow-y: scroll; border: 1px solid #ddd; border-radius: 3px">
            <t-cascader-panel
              v-model="formData.menus"
              check-strictly
              multiple
              :options="menus"
              :keys="{ label: 'name', value: 'id' }"
            ></t-cascader-panel>
          </div>
        </t-form-item>
      </t-form>
    </t-space>
  </t-dialog>
</template>
<script setup lang="ts">
import { ref } from 'vue';

import { t } from '@/locales';

import { FORM_DATA, FORM_RULES, FormItem } from '../constants';

defineProps({
  menus: {
    type: Array,
    default: () => [],
  },
});

const loading = ref(false);
const emits = defineEmits(['confirm']);

const dialogTitle = ref('');
const type = ref('add');
const visible = ref(false);
const form = ref(null);
const formData = ref({ ...FORM_DATA });

const dialogShow = (action: string, row: FormItem) => {
  visible.value = true;
  type.value = action;
  if (action === 'edit') {
    formData.value = JSON.parse(JSON.stringify(row));
    formData.value.menus = row.menus.map((v) => v.id);
    dialogTitle.value = `${t('common.edit')}【${row.name}】`;
  } else {
    dialogTitle.value = t('common.add');
  }
};
const dialogHide = () => {
  loading.value = false;
  form.value.reset();
  visible.value = false;
};
const dialogConfirm = async () => {
  const valid = await form.value.validate();
  if (valid !== true) {
    return;
  }
  loading.value = true;
  const res = JSON.parse(JSON.stringify(formData.value));
  res.menus = res.menus.map((v: Recordable) => {
    return { id: v };
  });

  emits('confirm', type.value, res);
};

defineExpose({
  dialogShow,
  dialogHide,
});
</script>
